package com.lee;

import javax.servlet.ServletException;
import javax.servlet.http.Part;
import java.io.IOException;
import java.sql.*;

public class Image {
     int id;

    public Image(int id) {
        this.id = id;
    }

    /**
     * 根据用户输入保存图片内容
     *
     * @param imagePart
     * @return
     */
    public static Image save(Part imagePart) throws IOException, ServletException {
        //1.通过JDBC保存图片内容
        try (Connection connection = DB.getConnection()) {
            String sql = "INSERT INTO images(image) VALUES (?)";
            try (PreparedStatement statement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
                statement.setBlob(1,imagePart.getInputStream(),imagePart.getSize());
                statement.executeUpdate();
                try (ResultSet resultSet=statement.getGeneratedKeys()){
                    if (resultSet.next()){
                        int id=resultSet.getInt(1);
                        return new Image(id);
                    }
                    return null;
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
            throw new ServletException(e);
        }
    }

    public static byte[] getById(int id) throws ServletException {
        try(Connection connection=DB.getConnection()){
            String sql="SELECT image FROM images WHERE id = ?";
            try (PreparedStatement statement=connection.prepareStatement(sql)){
                statement.setInt(1,id);
                try(ResultSet resultSet=statement.executeQuery()) {
                    if (resultSet.next()){
                        return resultSet.getBytes("image");
                    }else{
                        return null;
                    }
                }
            }
        }catch (SQLException e){
            e.printStackTrace();
            throw new ServletException(e);
        }
    }
}
